<?php
class ArrayToXML
{
    public static function toXML($data, $rootNodeName = 'EnviarInstrucao', &$xml=null)
    {
        if(ini_get('zend.ze1_compatibility_mode') == 1) ini_set('zend.ze1_compatibility_mode', 0);
        if(is_null($xml))
        {
            $xml = simplexml_load_string("<$rootNodeName/>");
            $rootNodeName = rtrim($rootNodeName, 's');
        }

        foreach($data as $key => $value)
        {
            $numeric = 0;
            if(is_numeric($key))
            {
                $numeric = 1;
                $key = $rootNodeName;
            }

            $key = preg_replace('/[^a-z0-9\-\.\:]/i', '', $key);

            if(is_array($value) && !is_null($value['attributes']))
            {
                $child = $xml->addChild($key, $value['value']);
                foreach($value['attributes'] as $k=>$v)
                {
                    $child->addAttribute($k, $v);
                }
            }
            elseif(is_array($value))
            {
                $node = (ArrayToXML::isAssoc($value) || $numeric) ? $xml->addChild($key) : $xml;

                if($numeric) $key = 'anon';
                ArrayToXML::toXml($value, $key, $node);
            }
            else
            {
                $xml->$key = $value;
            }
        }

        return $xml->asXML();
    }
     

    public static function isAssoc($array)
    {
        return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
    }
}